﻿using System;
using ThoughtWorks.CruiseControl.Core.Tasks.Conditions;
using NUnit.Framework;
using Rhino.Mocks;
using ThoughtWorks.CruiseControl.Core.Util;

namespace ThoughtWorks.CruiseControl.UnitTests.Core.Tasks.Conditions
{
    [TestFixture]
    public class UrlPingsTaskConditionTest
    {
        MockRepository mocks = new MockRepository();
        IWebFunctions webFunctions;

        [TestFixtureSetUp]
        public void testFixtureSetUp()
        {
            webFunctions = mocks.StrictMock<IWebFunctions>();
            Expect.Call(webFunctions.PingUrl(null)).Do(new urlExistsDelegate(Formal)).Repeat.Any();

            mocks.ReplayAll();
        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            mocks.VerifyAll();
        }

        delegate bool urlExistsDelegate(string filepath);
        private bool Formal(string filepath)
        {
            Uri url;
            if(Uri.TryCreate(filepath, UriKind.Absolute, out url))
                return url.ToString().Equals("http://www.testdomain.com/default.aspx", StringComparison.InvariantCultureIgnoreCase);

            return false;
        }

        private void executeTest(string address, bool expected)
        {
            UrlPingsTaskCondition condition = new UrlPingsTaskCondition();
            condition.Url = address;
            condition.WebFunctions = webFunctions;
            string message = "Tested '" + address + "' expected '" + expected + "'";
            Assert.That(condition.Eval(null), Is.EqualTo(expected), message);
        }

        [Test]
        [Description("BulkTest PassAll")]
        [Category("default")]
        public void UrlPingsTaskConditionTest_BulkTest_PassAll()
        {
            executeTest("http://www.testdomain.com/default.aspx", true);
            executeTest("http://www.TestDomain.com/default.aspx", true);
            executeTest("http://www.testDomain.com/default.aspx", true);
            executeTest("http://www.testdomain.com/Default.aspx", true);
            executeTest("http://www.testdomain.com/Testfolder/../default.aspx", true);
            executeTest("http://www.BugDomain.com/default.aspx", false);
            executeTest("http://www.BugDomain.com/Bug.aspx", false);
            executeTest("http://www.BugDomain.com/.aspx", false);
            executeTest("Not a url", false);
        }

        [Test]
        [Description("NullUrl ThrowArgumentNullException")]
        [Category("default")]
        [ExpectedException(typeof (System.NullReferenceException))]
        public void UrlPingsTaskConditionTest_NullUrl_ThrowArgumentNullException()
        {
            UrlPingsTaskCondition condition = new UrlPingsTaskCondition();
            condition.Url = null;
            condition.Eval(null);
        }
    }
}